﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace DataBGMonitor
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            iniInterface();
        }

        private void iniInterface()
        {
            string strDllPath = Application.StartupPath + "\\Plugin\\";
            int iBottom = 0;
            foreach(FileInfo fi in new DirectoryInfo(strDllPath ).GetFiles ("*.dll"))
            {
                if (fi.Exists )
                {
                    if (!IsRightPlug(fi.FullName))
                    {
                        continue;
                    }
                    ControlGroup cg = new ControlGroup();
                    cg.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))));
                    cg.Left = 10;
                    cg.Top = iBottom + 5;
                    iBottom = cg.Top + cg.Height;
                    cg.LoadDll(fi.FullName);
                    this.Controls.Add(cg);
                    cg.Visible = true;
                }
            }
        }

        private bool IsRightPlug(string strFileName)
        {
            Assembly ass;
            Type type;
            object obj;
            object objValue;
            try
            {
                ass = Assembly.LoadFile(strFileName);

                //加载程序集，命名空间必须为Plugin，类名必须为Config
                type = ass.GetType("Plugin.Config");

                PropertyInfo proinfo = type.GetProperty("ServiceName");

                obj = Activator.CreateInstance(type);

                objValue = proinfo.GetValue(obj, null);

                return true;
            }
            catch (Exception ex)
            {
                return false ;
            }
            finally
            {
                ass = null;
            }
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState==FormWindowState.Minimized)
            {
                this.WindowState= FormWindowState.Normal;
                this.Visible = false;
                notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!this.Visible)
            {
                this.WindowState = FormWindowState.Normal;
                this.Show();
                notifyIcon1.Visible = false;
            }
        }
    }
}
